package tk.mybatis.web.webSocket;
import com.alibaba.fastjson.JSON;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

//该类针对所有客户端连接只创建一个实例
public class WebSocketEndPoint extends TextWebSocketHandler {

    public WebSocketEndPoint(){
        random = Math.random();
    }
    private Double random;

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        WebSocketPool.sendMessage("回复" + message.getPayload());
    }
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        WebSocketPool.addConnection(session, "");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        WebSocketPool.removeConnection(session);
    }

    public <T> void send(WebSocketSession session,T message) throws IOException {
        TextMessage returnMessage;
        if (message instanceof String) {
            returnMessage = new TextMessage((String) message);
        }
        else {
            returnMessage = new TextMessage(JSON.toJSONString(message));
        }
        session.sendMessage(returnMessage);
    }
}